﻿using Lamex.Base;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Lamex.mPE.UI
{
    public partial class FrmPE_PN_AL_BatchModeling : Form
    {
        string strCurPath, strTmpPath, strCurModule, strResult, strNewFile;
        public FrmPE_PN_AL_BatchModeling()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            #region //选择模型文件路径
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            dialog.ShowNewFolderButton = false;
            dialog.Description = "请选择模型文件路径，拆分实例保存在同级路径：" + "\r\n" + "再次实例化前请先删除旧文件！";
            dialog.SelectedPath = @"L:\Parametric\Sample";
            //dialog.RootFolder = Environment.SpecialFolder.MyComputer;
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                strCurPath = dialog.SelectedPath;
                strCurModule = strCurPath.Substring(strCurPath.LastIndexOf("\\") + 1, strCurPath.Length - strCurPath.LastIndexOf("\\") - 1);
                strTmpPath = strCurPath.Substring(0, strCurPath.Length - strCurModule.Length - 1) + "\\Temp";
                if (Directory.Exists(strTmpPath))//文件夹存在
                {
                    DirectoryInfo di = new DirectoryInfo(strTmpPath);
                    di.Delete(true);//删除里面所有的文件，包括文件夹和子文件夹
                }
                Directory.CreateDirectory(strTmpPath);//创建文件夹
            }
            else
            {
                return;
            }
            #endregion

            #region //获取处理清单

            //            string sql = @"SELECT * FROM [LamexMESManager].[dbo].[NC_PN_AL_Detail_Part]
            //                            WHERE DRAWING_NO = '" + strCurModule + "'" +
            //                            "ORDER BY PART_NO";

            //string sql = @"select a.*,b.CREO_VALUE_TYPE from 
            //            (select p.DRAWING_NO + '_' + p.PARAMETER_NAME as DWG_PAR,p.* from NC_PN_AL_Detail_Part p) a 
            //            left join 
            //            (select d.DRAWING_NO + '_' + d.PARAMETER_NAME as DWG_PAR,d.CREO_VALUE_TYPE from NC_PN_AL_Detail_Drawing d) b 
            //            on b.DWG_PAR=a.DWG_PAR
            //            where a.DRAWING_NO='" + strCurModule + "'";

            //增加按PART_NO排序，避免因多参数图纸（A6FA248A）创建文件夹时报错中断，2020/6/18 Rocky
            string sql = @"select a.*,b.CREO_VALUE_TYPE from 
                        (select p.DRAWING_NO + '_' + p.PARAMETER_NAME as DWG_PAR,p.* from NC_PN_AL_Detail_Part p) a 
                        left join 
                        (select d.DRAWING_NO + '_' + d.PARAMETER_NAME as DWG_PAR,d.CREO_VALUE_TYPE from NC_PN_AL_Detail_Drawing d) b 
                        on b.DWG_PAR=a.DWG_PAR
                        where a.DRAWING_NO='" + strCurModule + @"'
                        order by PART_NO";

            DataTable dt = BaseBuildSql.GetDataTableBySql(sql);

            #endregion

            if (dt.Rows.Count != 0)
            {
                #region //拆分实例模型
                string prePART_NO = "", curPART_NO = "", curMODEL_NO = "", strParFile = "";
                string strParList = "", strCfgList = "";
                string parName = "", parValue = "";

                strCfgList = @"mapkey pmd ~ Command `ProCmdModelEraseNotDisp` ;\" + "\r\n";

                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    curPART_NO = dt.Rows[i]["PART_NO"].ToString();

                    if (curPART_NO != prePART_NO)//不同部件才进行拆分                
                    {
                        if (strParList != "")
                        {
                            File.WriteAllText(strParFile, strParList, Encoding.UTF8);
                            strParList = "";
                        }

                        prePART_NO = curPART_NO;
                        curMODEL_NO = strCurModule + "_" + curPART_NO;
                        var newPath = strTmpPath + "\\" + curMODEL_NO;
                        strParFile = newPath + "\\" + curMODEL_NO + ".txt";

                        strParList = strParList + "PART_NO = " + "\"" + curPART_NO + "\"" + "\r\n";

                        parName = dt.Rows[i]["PARAMETER_NAME"].ToString();
                        parValue = dt.Rows[i]["PARAMETER_VALUE"].ToString();

                        if (dt.Rows[i]["CREO_VALUE_TYPE"].ToString() == "String")
                        {
                            strParList = strParList + parName + " = " + "\"" + parValue + "\"" + "\r\n";
                        }
                        else
                        {
                            strParList = strParList + parName + " = " + parValue + "\r\n";
                        }

                        //复制所有文件
                        Directory.CreateDirectory(newPath);
                        string[] filenames = Directory.GetFileSystemEntries(strCurPath);
                        foreach (string file in filenames)
                        {
                            strNewFile = file.Substring(file.LastIndexOf("\\") + 1, file.Length - file.LastIndexOf("\\") - 1);
                            File.Copy(file, newPath + "\\" + strNewFile);
                        }

                        strCfgList = strCfgList
                        + @"mapkey(continued) ~ Activate `file_erase_nd` `ok_pb`;~ Command `ProCmdSessionChangeDir` ;\" + "\r\n"
                        + @"mapkey(continued) ~ Trail `UI Desktop` `UI Desktop` `DLG_PREVIEW_POST` `file_open`;\" + "\r\n"
                        + @"mapkey(continued) ~ Update `file_open` `Inputname` \" + "\r\n"
                        + @"mapkey(continued) `" + @newPath.Replace(@"\", @"\\") + @"`;\" + "\r\n"
                        + @"mapkey(continued) ~ Command `ProFileSelPushOpen@context_dlg_open_cmd` ;\" + "\r\n"
                        + @"mapkey(continued) ~ Command `ProCmdModelOpen` ;\" + "\r\n"
                        + @"mapkey(continued) ~ Trail `UI Desktop` `UI Desktop` `DLG_PREVIEW_POST` `file_open`;\" + "\r\n"
                        + @"mapkey(continued) ~ Update `file_open` `Inputname` `" + strCurModule + @"`;\" + "\r\n"
                        + @"mapkey(continued) ~ Command `ProFileSelPushOpen_Standard@context_dlg_open_cmd` ;\" + "\r\n"
                        + @"mapkey(continued) ~ Close `main_dlg_cur` `appl_casc`;~ Command `ProCmdModelRename` ;\" + "\r\n"
                        + @"mapkey(continued) ~ Update `rename` `InputPanel2` `" + curMODEL_NO + @"`;\" + "\r\n"
                        + @"mapkey(continued) ~ Activate `rename` `OK`;~ Command `ProCmdRegenPart` ;#READ FILE;\" + "\r\n"
                        + @"mapkey(continued) " + strParFile + @";\" + "\r\n";

                        //因增加自动切换当前工作目录快捷指令，所以代码注释掉，2019-12-24
                        //if (i != dt.Rows.Count - 1)
                        //{
                        strCfgList = strCfgList + @"mapkey(continued) ~ Command `ProCmdModelSave` ;~ Command `ProCmdWinCloseGroup`;\" + "\r\n";
                        //}
                        //else
                        //{
                        //strCfgList = strCfgList + @"mapkey(continued) ~ Command `ProCmdModelSave` ;~ Command `ProCmdWinCloseGroup`;" + "\r\n";
                        //}
                    }
                    else
                    {
                        strParList = strParList + dt.Rows[i]["PARAMETER_NAME"].ToString() + " = " + dt.Rows[i]["PARAMETER_VALUE"].ToString() + "\r\n";
                    }
                }

                //增加自动切换当前工作目录到D:\快捷指令，2019-12-24
                strCfgList = strCfgList
                + @"mapkey(continued) ~ Command `ProCmdSessionChangeDir` ;\" + "\r\n"
                + @"mapkey(continued) ~ Trail `UI Desktop` `UI Desktop` `DLG_PREVIEW_POST` `file_open`;\" + "\r\n"
                + @"mapkey(continued) ~ Activate `file_open` `computer_pb`;\" + "\r\n"
                + @"mapkey(continued) ~ Select `file_open` `Ph_list.Filelist` 1 `d:`;\" + "\r\n"
                + @"mapkey(continued) ~ Command `ProFileSelPushOpen@context_dlg_open_cmd`;" + "\r\n"
                + @"" + "\r\n"
                + @"" + "\r\n";

                //最后一个部件参数文件输出
                File.WriteAllText(strParFile, strParList, Encoding.UTF8);

                #endregion

                #region //生成批处理命令配置文件

                //切换标准配置文件命令输出
                strCfgList = strCfgList + "\r\n"
                + @"mapkey cf ~ Select `main_dlg_cur` `appl_casc`;\" + "\r\n"
                + @"mapkey(continued) ~ Close `main_dlg_cur` `appl_casc`;~ Command `ProCmdRibbonOptionsDlg` ;\" + "\r\n"
                + @"mapkey(continued) ~ Select `ribbon_options_dialog` `PageSwitcherPageList` 1 `ConfigLayout`;\" + "\r\n"
                + @"mapkey(continued) ~ Select `ribbon_options_dialog` `ConfigLayout.ImportExportBtn`;\" + "\r\n"
                + @"mapkey(continued) ~ Close `ribbon_options_dialog` `ConfigLayout.ImportExportBtn`;\" + "\r\n"
                + @"mapkey(continued) ~ Activate `ribbon_options_dialog` `ConfigLayout.Open`;\" + "\r\n"
                + @"mapkey(continued) ~ Trail `UI Desktop` `UI Desktop` `DLG_PREVIEW_POST` `file_open`;\" + "\r\n"
                + @"mapkey(continued) ~ Activate `main_dlg_cur` `main_dlg_cur`;\" + "\r\n"
                + @"mapkey(continued) ~ Update `file_open` `Inputname` `Z:\\Sta\\Rocky he\\Config.pro`;\" + "\r\n"
                + @"mapkey(continued) ~ Command `ProFileSelPushOpen_Standard@context_dlg_open_cmd` ;\" + "\r\n"
                + @"mapkey(continued) ~ Activate `ribbon_options_dialog` `OkPshBtn`;\" + "\r\n"
                + @"mapkey(continued) ~ FocusIn `UITools Msg Dialog Future` `no`;\" + "\r\n"
                + @"mapkey(continued) ~ Activate `UITools Msg Dialog Future` `no`;" + "\r\n";

                //批量抽取特征数据时不能识别数字版本，所以设置直接保存
                strCfgList = strCfgList + "\r\n"
                + @"save_file_iterations no" + "\r\n";

                File.WriteAllText(@"D:\Config_Temp.pro", strCfgList, Encoding.UTF8);
                #endregion

                MessageBox.Show("在Creo环境下，输入ct导入临时配置文件，用pmd命令完成实例模型刷新！");
            }
            else
            {
                MessageBox.Show("未找到【" + strCurModule + "】部件参数清单，请先维护！");
            }

            this.Close();
        }
    }
}
